package com.rg.inf.action;

import java.util.List;

import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.dto.client.sync.ClientActivateMsgBody;
import com.rd.sys.dto.client.sync.MsgBody;
import com.rd.sys.dto.commmon.base.EyeException;
import com.rd.sys.dto.commmon.base.EyeResult;
import com.rd.sys.dto.commmon.enums.SubActivationEnum;
import com.rd.sys.dto.sys.user.UserInfoDto;
import com.rd.sys.dto.sys.user.UserSubActivationDto;
import com.rd.sys.service.sys.user.UserAllInOneService;

public class ClientActivateAction extends BaseExecuteAction {
    protected UserAllInOneService userAllInOneService = (UserAllInOneService) getService("userAllInOneServiceImpl");

    @Override
    public EyeResult execute(UserInfoDto userInfo, MsgBody msgBody, Object... objs) throws EyeException, Exception {
        ClientActivateMsgBody body = (ClientActivateMsgBody) msgBody;

        /** 1.检查订购关系是否正常 */
        // 专业版不检查订购关系

        /** 2.查询出 该订购关系的所有激活码 */

        List<UserSubActivationDto> activeList = userAllInOneService.findUserActivation(userInfo.getUsercode());

        /** 3.判断激活码是否存在 */
        boolean hasActive = false;
        UserSubActivationDto active = null;
        for (int i = 0; i < activeList.size(); i++) {
            if (activeList.get(i).getActivationcode().equals(body.getActivationCode())) {
                hasActive = true; // 找到激活码
                active = activeList.get(i);
            }
        }

        if (!hasActive) { // 未找到激活码
            throw new EyeException(EyeResult.ResultDefine.ACTIVATE_AUTH_CODE_ERROR);
        }

        /** 4.判断激活码是否已被注册or是否是该MAC地址 */
        if (SubActivationEnum.Status.UNUSED.getCode().equals(active.getStatus().toString())) {
            // 允许注册,更新状态
            active.setMac(body.getMacAddress()); // MAC地址更新为注册时的
            userAllInOneService.updateActivationToUsed(userInfo.getUsercode(), active);
        } else {
            boolean alreadyActived = false; // 是否已激活且MAC地址正确标识
            String[] msgMacs = body.getMacAddress().split(CommonConstants.UserConstats.CLIENT_ACTIVATE_MAC_SPLIT_SIGN);
            for (String mac : msgMacs) { // 遍历消息中的所有MAC地址,有其一在注册时的MAC地址中则表示正确
                if (active.getMac().contains(mac)) {
                    alreadyActived = true;
                    break;
                }
            }

            if (!alreadyActived) {
                // 已注册,但消息中的MAC地址均未在注册时上传的MAC地址之中
                throw new EyeException(EyeResult.ResultDefine.ACTIVATE_AUTH_MAC_ERROR);
            }
        }

        return new EyeResult(EyeResult.ResultDefine.COMMON_SUCCESS);
    }
}
